#include<vector>
#include<unordered_map>
#include<queue>
using namespace std;
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> hash;
        for (auto e : nums)
            hash[e]++;
        auto compare = [&hash](int x, int y) {return hash[x] > hash[y]; };
        priority_queue<int, vector<int>, decltype(compare)> minHeap(compare);
        for (auto e : hash) {
            if (minHeap.size() < k)
                minHeap.push(e.first);
            else {
                if (e.second > hash[minHeap.top()]) {
                    minHeap.pop();
                    minHeap.push(e.first);
                }
            }
        }
        vector<int> res;
        while (!minHeap.empty()) {
            res.push_back(minHeap.top());
            minHeap.pop();
        }
        return res;
    }
};